package br.biofoco.p2p.rpc;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;


public final class InetAddressUtil {
	
	private InetAddressUtil() {}
	
	/**
	 * 
	 * @return A immutable collection of non-loopback IPv4 InetAddress, if any or an empty set otherwise.
	 * @throws SocketException
	 */
	public static List<InetAddress> getLocalAddresses() throws SocketException {
		
		final List<InetAddress> ipSet = new ArrayList<InetAddress>();
		
		System.setProperty("java.net.preferIPv4Stack", "true");

		Enumeration<NetworkInterface> enumerate = NetworkInterface.getNetworkInterfaces();
		
		while (enumerate.hasMoreElements()) {
			NetworkInterface nitf = enumerate.nextElement();

			Enumeration<InetAddress> list = nitf.getInetAddresses();
			
			while (list.hasMoreElements()) {
				InetAddress addr = list.nextElement();
				if (!addr.isLoopbackAddress()) {
					ipSet.add(addr);
				}
			}			
		}
		
		System.setProperty("java.net.preferIPv4Stack", "false");		
		
		return Collections.unmodifiableList(ipSet);
	}

}
